/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package crawler.admin.controller;

import crawler.common.CateData;
import crawler.common.CommonUtil;
import crawler.common.RenderModel;
import crawler.common.UserRole;
import crawler.model.CateModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author ngotandieu
 */
public class AdminCateController extends HttpServlet {

    private static final Logger logger = Logger.getLogger(AdminCateController.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if (!CommonUtil.checkSession(req, resp)) {
                return;
            }
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminCateController.handle:" + ex.getMessage(), ex);
        }
    }

    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {
            case "/ajax-add-new-cate":
                content = ajaxAddNewCate(req, resp);
                break;
            case "/ajax-edit-cate":
                content = ajaxEditCate(req, resp);
                break;
            case "/ajax-delete-cate":
                content = ajaxDeleteCate(req, resp);
                break;
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }

    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.CATEGORY)) {
                resp.sendRedirect("/");
                return "";
            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "profile_cate"));
            dic.setVariable("PAGE_TITLE", "Danh mục");

            CateModel cateModel = CateModel.getInstance();
            List<CateData> lstCate = cateModel.getCate(0, -1);
            if (lstCate != null && !lstCate.isEmpty()) {
                for (CateData cateData : lstCate) {
                    TemplateDataDictionary section = dic.addSection("LIST_CATE");
                    section.setVariable("CATE_ID", String.valueOf(cateData.getId()));
                    section.setVariable("CATE_NAME", cateData.getName());
                }
            }

            if (CommonUtil.checkAccess(req, UserRole.CATEGORY_EDIT)) {
                dic.showSection("CATEGORY_EDIT");
            }

            Template template = RenderModel.getAdminCTemplate("cate_page");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminCateController.renderIndexPage: " + ex.getMessage(), ex);
        }
        return content;
    }

    private String ajaxAddNewCate(HttpServletRequest req, HttpServletResponse resp) {
        int error = 0;
        String msg = "Thêm danh mục thành công.";
        Map<String, String> data = new HashMap<>();
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
            if (!CommonUtil.checkAccess(req, UserRole.CATEGORY_EDIT)) {
                return CommonUtil.toPermissionDenied();
            }

            String name = req.getParameter("name") != null ? req.getParameter("name") : "";
            if (name.equalsIgnoreCase("")) {
                msg = "Tên danh mục không được trống.";
                error = -1;
            }

            if (error == 0) {
                CateModel cateModel = CateModel.getInstance();
                CateData cateData = new CateData();
                cateData.setName(name);
                String addCate = cateModel.addCate(cateData);
                if (addCate.equalsIgnoreCase("")) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
                data.put("id", String.valueOf(addCate));
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        return CommonUtil.toJSON(error, msg, data);
    }

    private String ajaxEditCate(HttpServletRequest req, HttpServletResponse resp) {
        int error = 0;
        String msg = "Chỉnh sửa danh mục thành công.";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
            if (!CommonUtil.checkAccess(req, UserRole.CATEGORY_EDIT)) {
                return CommonUtil.toPermissionDenied();
            }

            String id = req.getParameter("pk") != null ? req.getParameter("pk") : "";
            String name = req.getParameter("value") != null ? req.getParameter("value") : "";

            if (id.equalsIgnoreCase("")) {
                msg = "Id danh mục không được trống.";
                error = -1;
            }

            if (name.equalsIgnoreCase("")) {
                msg = "Tên danh mục không được trống.";
                error = -1;
            }

            if (error == 0) {
                CateModel cateModel = CateModel.getInstance();
                CateData cateData = new CateData(id, name, 0);
                boolean editCate = cateModel.editCate(cateData);
                if (!editCate) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        return CommonUtil.toJSON(error, msg);
    }

    private String ajaxDeleteCate(HttpServletRequest req, HttpServletResponse resp) {
        int error = 0;
        String msg = "Xoá danh mục thành công.";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
            if (!CommonUtil.checkAccess(req, UserRole.CATEGORY_EDIT)) {
                return CommonUtil.toPermissionDenied();
            }

            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            if (id.equalsIgnoreCase("")) {
                msg = "Id danh mục không được trống.";
                error = -1;
            }

            if (error == 0) {
                CateModel cateModel = CateModel.getInstance();
                boolean deleteCate = cateModel.deleteCate(id);
                if (!deleteCate) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        return CommonUtil.toJSON(error, msg);
    }

}
